package com.rpframework.website.friendly.act.api;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rpframework.core.BaseAct;
import com.rpframework.core.api.FileService;
import com.rpframework.core.utils.DictionarySettingUtils;
import com.rpframework.core.utils.MessageFormatter;
import com.rpframework.core.utils.TagUtils;
import com.rpframework.module.common.service.CountyService;
import com.rpframework.module.common.service.SMSService;
import com.rpframework.utils.DateUtils;
import com.rpframework.utils.NumberUtils;
import com.rpframework.website.friendly.domain.User;
import com.rpframework.website.friendly.exception.APICodeException;
import com.rpframework.website.friendly.service.UserService;
import com.rpframework.website.friendly.util.HConstants;

/**
 * 用户接口
 * @author zl
 * @date 2015年12月14日 下午5:56:29
 */
@Controller
@RequestMapping("/api/user")
public class UserApiAct extends BaseAct {
	Gson gson = new Gson();
	@Resource UserService userService;
	@Resource FileService fileService;
	@Resource SMSService smsService;
	@Resource CountyService countyService;
	
	@RequestMapping("userdata")
	public @ResponseBody JsonElement execute(HttpSession session, HttpServletRequest request){
		User user = getSessionUser(session);
		return select(user.getId());
	}
	
	@RequestMapping("/data")
	public @ResponseBody JsonElement Date(
			@RequestParam(value="userId",required=false) Integer userId,
			@RequestParam(value="remark",required=false) String remark
			//HttpSession session, HttpServletRequest request
			){
		//User user = getSessionUser(session);
		if(NumberUtils.isNotValid(userId))return ThrowsParamException("userId");
		//User user = userService.select(userId);
		JsonObject json = new JsonObject();
		if(remark!=null && "Y".equals(remark.toUpperCase()))
			json.add("remark",getJsonInfo());
		
		return json;
	}
	
	private JsonElement getJsonInfo() {
		JsonObject json = new JsonObject();
		json.addProperty("id", "用户id");
		json.addProperty("headImg", "头像");
		json.addProperty("nickName", "昵称");
		json.addProperty("friendlyNo", "友邻号");
		json.addProperty("contact", "手机号");
		json.addProperty("qrCode", "二维码");
		json.addProperty("sex", "性别");
		json.addProperty("", "地区,我的地址(默认的取城市)");
		json.addProperty("signName", "个人签名");
		json.addProperty("", "我的地址(默认的)");
		return json;
	}

	/**
	 * 发送修改手机验证码
	 * @param contact
	 * @return
	 */
	@RequestMapping("/sendsms_for_change_contact")
	public @ResponseBody JsonElement sendSMS4ChangeContact(@RequestParam(required=false) String contact, HttpSession session, HttpServletRequest request) {
		if(StringUtils.isBlank(contact)) {
			throw new IllegalArgumentException("非法参数!");
		}
		
		String verifyCode = String.valueOf(NumberUtils.random(6));
		String sendContent = DictionarySettingUtils.getParameterValue("sendsms.change_contact");
		if(StringUtils.isBlank(sendContent)) {
			sendContent =  "本次修改手机号验证码:{}，请牢记";
		}
		sendContent = MessageFormatter.format(sendContent, verifyCode);
		
		boolean flag = smsService.sendSMS(HConstants.ChannelType.SEND_SMS_CHANGE_CONTACT_CHANNEL_TYPE, contact, verifyCode, sendContent);
		if(!flag) {
			throw new IllegalArgumentException("短信发送失败!");
		}
		JsonObject json = new JsonObject();
		json.addProperty("succ", true);
		return json;
	}
	
	/**
	 * 修改手机号
	 * @param newContact
	 * @param verifyCode
	 * @return
	 */
	@RequestMapping("/change_contact")
	public @ResponseBody JsonElement changeContact(@RequestParam String newContact,@RequestParam String verifyCode, HttpSession session, HttpServletRequest request) {
		User user = getSessionUser(session);
		if(StringUtils.isBlank(newContact) || StringUtils.isBlank(verifyCode)) {
			throw new IllegalArgumentException("非法参数!");
		}
		
		String oldContact = user.getContact();
		if(StringUtils.equals(newContact, oldContact)) {
			throw new IllegalArgumentException("手机号相同!");
		}
		
		if(!smsService.checkVerifyCode(HConstants.ChannelType.SEND_SMS_CHANGE_CONTACT_CHANNEL_TYPE, oldContact, verifyCode)) {
			throw new IllegalArgumentException("验证码不正确!");
		}
		
		User newContactUser = userService.findUserByContact(newContact);
		if(newContactUser != null) {
			throw new IllegalArgumentException("新的手机号码已经注册为本站的会员!");
		}
		
		user.setContact(newContact);
		userService.update(user);
		
		smsService.setVerifyCodeVaild(HConstants.ChannelType.SEND_SMS_FORGET_PASSWORD_CHANNEL_TYPE, oldContact);
		
		JsonObject json = new JsonObject();
		json.addProperty("succ", true);
		return json;
	}

	/**
	 * 修改密码
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequestMapping("/change_pwd")
	public @ResponseBody JsonElement changePwd(@RequestParam String oldPassword,@RequestParam String newPassword, HttpSession session, HttpServletRequest request) {
		User user = getSessionUser(session);
		boolean flag = userService.changePassword(user, oldPassword, newPassword);
		JsonObject json = new JsonObject();
		json.addProperty("succ", flag);
		return json;
	}
	
	/**
	 * 修改头像
	 * @param headImgFile
	 * @return
	 */
	@RequestMapping("/change_head_img")
	public @ResponseBody JsonElement changeHeadImg(@RequestParam(value="headImgFile", required=false) MultipartFile headImgFile, HttpSession session, HttpServletRequest request){
		User user = getSessionUser(session);
		if(!headImgFile.isEmpty()) {
			try {
				String relativelyPath = "resources/head/" + DateUtils.nowDate(DateUtils.YYYYMMDDHHMMSS) + NumberUtils.random() + "." + FilenameUtils.getExtension(headImgFile.getOriginalFilename());
				fileService.saveFile(headImgFile.getInputStream(), relativelyPath);
				user.setHeadImg(relativelyPath);
				userService.update(user);
				
				JsonObject json = new JsonObject();
				json.addProperty("succ", true);
				json.addProperty("headImg", TagUtils.getFileFullPath(relativelyPath));
				return json;
			} catch (Exception e) {
				throw new IllegalArgumentException("文件上传失败，原因:" + e.getLocalizedMessage());
			}
		}
		
		throw new IllegalArgumentException("参数错误!");
	}
	
	/**
	 * 修改真实姓名
	 * @param realName
	 * @return
	 */
	@RequestMapping("/change_real_name")
	public @ResponseBody JsonElement changeRealName(@RequestParam String realName,  HttpSession session, HttpServletRequest request){
		User user = getSessionUser(session);
		user.setRealName(realName);
		userService.update(user);
		JsonObject json = new JsonObject();
		json.addProperty("succ", true);
		return json;
	}
	
	/**
	 * 修改真实姓名
	 * @param realName
	 * @return
	 */
	@RequestMapping("/change_user_name")
	public @ResponseBody JsonElement changeUserName(@RequestParam String userName,  HttpSession session, HttpServletRequest request){
		User user = getSessionUser(session);
		user.setUserName(userName);
		userService.update(user);
		JsonObject json = new JsonObject();
		json.addProperty("succ", true);
		return json;
	}
	
	
	/**
	 * 根据用户ID查询用户信息
	 * @param userId
	 * @return
	 */
	@RequestMapping("/{userId}/select")
	public @ResponseBody JsonElement select(@PathVariable Integer userId) {
		User user = userService.select(userId);
		if(user == null){
			throw new APICodeException(-1, "不存在的ID: " + userId);
		}
		return packageUserJson(user);
	}
	
	public JsonElement packageUserJson(User user) {
		JsonObject json = new JsonObject();
		json.addProperty("userId", user.getId());
		json.addProperty("userName", user.getUserName());
		json.addProperty("realName", user.getRealName());
		json.addProperty("contact", user.getContact());
		json.addProperty("headImg", TagUtils.getFileFullPath(user.getHeadImg()));
	//	json.addProperty("money", user.getUserMoney().getMoney());
		return json;
	}
	

}
